package com.example.testcalendaractivity;

import static android.provider.CalendarContract.Events.*;


import static com.example.testcalendaractivity.util.SharedValues.MAX_DESCRIPTION_LENGTH;
import static com.example.testcalendaractivity.util.SharedValues.MAX_EVENT_NUMBER;
import static com.example.testcalendaractivity.util.SharedValues.MAX_TITLE_LENGTH;

import android.annotation.SuppressLint;
import android.app.DatePickerDialog;
import android.app.TimePickerDialog;
import android.content.ContentResolver;
import android.content.ContentUris;
import android.content.ContentValues;
import android.content.Intent;
import android.database.Cursor;
import android.net.Uri;
import android.os.Bundle;
import android.provider.CalendarContract;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.RadioGroup;
import android.widget.TextView;
import android.widget.Toast;

import androidx.activity.EdgeToEdge;
import androidx.appcompat.app.AppCompatActivity;

import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.Locale;
import java.util.TimeZone;

public class EditEventActivity extends AppCompatActivity implements View.OnClickListener {
    private EditText editTitle, editLocation, editContent;
    private TextView editStart, editEnd;
    private Button btnDeleteEvent, btnEditEvent, btnEditBack, pickButton, pickButtonEnd;
    private long eventId;
    private Calendar calendar = Calendar.getInstance();
    private RadioGroup freqPick;
    Calendar start = Calendar.getInstance();
    Calendar end = Calendar.getInstance();

    private static final String DAILY = "DAILY";
    private static final String WEEKLY = "WEEKLY";
    private static final String MONTHLY = "MONTHLY";
    private static final String YEARLY = "FREQ=YEARLY;";

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
//        EdgeToEdge.enable(this);
        setContentView(R.layout.activity_edit_event);
        //初始化控件
        editTitle = findViewById(R.id.editTitle);
        editLocation = findViewById(R.id.editLocation);
        editContent = findViewById(R.id.editContent);
        editStart = findViewById(R.id.date_text);
        editEnd = findViewById(R.id.date_text_end);
        btnDeleteEvent = findViewById(R.id.btn_deleteEvent);
        btnEditEvent = findViewById(R.id.btn_edit);
        btnEditBack = findViewById(R.id.back_button);
        pickButton = findViewById(R.id.pick_button);
        pickButtonEnd = findViewById(R.id.pick_button_end);
        freqPick = findViewById(R.id.rg2);

        editTitle.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {
            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
            }

            @Override
            public void afterTextChanged(Editable s) {
                if (s.length() > MAX_TITLE_LENGTH) {
                    s.delete(MAX_TITLE_LENGTH, s.length()); // 删除超出部分
                }
            }
        });
        editContent.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {
            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
            }

            @Override
            public void afterTextChanged(Editable s) {
                if (s.length() > MAX_DESCRIPTION_LENGTH) {
                    s.delete(MAX_DESCRIPTION_LENGTH, s.length()); // 删除超出部分
                }
            }
        });

        //获取点击事件的信息
        Intent intent = getIntent();
        eventId = intent.getLongExtra("eventId", -1);
        String title = intent.getStringExtra("eventTitle");
        long startDate = intent.getLongExtra("eventStartDate", -1);
        long endDate = intent.getLongExtra("eventEndDate", -1);
        String description = intent.getStringExtra("eventDescription");
        String location = intent.getStringExtra("eventLocation");
        String rule = intent.getStringExtra("rrule");
        //显示事件信息
        editTitle.setText(title);
        editStart.setText(formatDate(startDate));
        editEnd.setText(formatDate(endDate));
        editContent.setText(description);
        editLocation.setText(location);

        if (rule == null) {
            freqPick.check(R.id.btn_once2);
        } else if (rule.contains(DAILY)) {
            freqPick.check(R.id.btn_daily2);
        } else if (rule.contains(WEEKLY)) {
            freqPick.check(R.id.btn_weekly2);
        } else if (rule.contains(MONTHLY)) {
            freqPick.check(R.id.btn_monthly2);
        } else if (rule.contains(YEARLY)) {
            freqPick.check(R.id.btn_yearly2);
        }

        //返回监听
        btnEditBack.setOnClickListener(this);
        //日期选择监听
        editStart.setOnClickListener(this);
        pickButton.setOnClickListener(this);
        editEnd.setOnClickListener(this);
        pickButtonEnd.setOnClickListener(this);

        // 设置删除按钮点击监听
        btnDeleteEvent.setOnClickListener(v -> deleteEvent(eventId, startDate));

        //设置修改按钮点击监听
        btnEditEvent.setOnClickListener(v -> {
            //获取用户输入的新事件信息
            String newTitle = editTitle.getText().toString();
            String stime = editStart.getText().toString();
            String dtime = editEnd.getText().toString();
            SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm");
            int repeatOptionId = freqPick.getCheckedRadioButtonId();

            long newStartDate = 0;
            try {
                newStartDate = dateFormat.parse(stime).getTime();
            } catch (ParseException e) {
                throw new RuntimeException(e);
            }
            long newEndDate = 0;
            try {
                newEndDate = dateFormat.parse(dtime).getTime();
            } catch (ParseException e) {
                throw new RuntimeException(e);
            }

            String newContent = editContent.getText().toString();
            String newLocation = editLocation.getText().toString();

            // 修改后事件年月日与之前相同，先删除后添加
            ContentResolver cr = getContentResolver();
            Uri eventUri = ContentUris.withAppendedId(CONTENT_URI, eventId);
            Cursor cursor = cr.query(eventUri, new String[]{CalendarContract.Events.DTSTART}, null, null, null);
            if (cursor != null && cursor.moveToFirst()) {
                @SuppressLint("Range") long oldStartDate = cursor.getLong(cursor.getColumnIndex(CalendarContract.Events.DTSTART));
                boolean sameDay = isSameDay(oldStartDate, newStartDate);
                if (sameDay) {
                    updateEvent(eventId, newTitle, newStartDate, newEndDate, newContent, newLocation, repeatOptionId);
                    return;
                } else {
                    try {
                        if (ifEventReachedMax()) {
                            return;
                        }
                    } catch (ParseException e) {
                        throw new RuntimeException(e);
                    }
                }
            }
            //更新事件
            updateEvent(eventId, newTitle, newStartDate, newEndDate, newContent, newLocation, repeatOptionId);
        });
    }

    @Override
    public void onClick(View v) {
        if (v.getId() == R.id.back_button) {

            finish();
        } else if (v.getId() == R.id.pick_button || v.getId() == R.id.date_text || v.getId() == R.id.pick_button_end || v.getId() == R.id.date_text_end) {
            datePick(v);
        }
    }

    //删除事件
    private void deleteEvent(long eventId,long startDate) {
        ContentResolver cr = getContentResolver();
        Uri deleteUri = ContentUris.withAppendedId(CONTENT_URI, eventId);
        int rows = cr.delete(deleteUri, null, null);
        if (rows > 0) {
            Toast.makeText(this, "Event: " + eventId + " deleted.", Toast.LENGTH_SHORT).show();
        }
        Intent resultIntent = new Intent();
        resultIntent.putExtra("selectedDate",startDate);
        setResult(RESULT_OK,resultIntent);
        finish();
    }

    // 修改事件
    private void updateEvent(long eventId, String title, long startDate, long endDate, String des, String location, int repeatedId) {
        if (title.isEmpty()) {
            Toast.makeText(this, "请输入标题！", Toast.LENGTH_LONG).show();
            return;
        }
        //删除旧的
        deleteEvent(eventId,startDate);

        //插入新的
        ContentResolver cr = getContentResolver();
        ContentValues values = new ContentValues();

        //
        String selectedCalendar = "ADBC_calendar";
        long calendarId = getCalendarId(selectedCalendar);

        values.put(CalendarContract.Events.DTSTART, startDate);
        values.put(CalendarContract.Events.DTEND, endDate);
        values.put(CalendarContract.Events.TITLE, title);
        values.put(CalendarContract.Events.DESCRIPTION, des);
        values.put(CalendarContract.Events.EVENT_LOCATION, location);
        values.put(CalendarContract.Events.CALENDAR_ID, calendarId); // 获取指定日历id
        values.put(CalendarContract.Events.EVENT_TIMEZONE, "Asia/Shanghai");

        Calendar calendar = Calendar.getInstance(TimeZone.getTimeZone("UTC"));
        calendar.setTimeInMillis(startDate);
        calendar.add(Calendar.YEAR, 10); // 加上10年
        String untilDate = new SimpleDateFormat("yyyyMMdd'T'HHmmss'Z'").format(calendar.getTime());

        if (repeatedId == R.id.btn_daily2) {
            values.put(CalendarContract.Events.RRULE, "FREQ=DAILY");
        } else if (repeatedId == R.id.btn_weekly2) {
            values.put(CalendarContract.Events.RRULE, "FREQ=WEEKLY");
        } else if (repeatedId == R.id.btn_monthly2) {
            values.put(CalendarContract.Events.RRULE, "FREQ=MONTHLY");
        } else if (repeatedId == R.id.btn_yearly2) {
            values.put(CalendarContract.Events.RRULE, "FREQ=YEARLY");
        }

        Uri uri = cr.insert(CONTENT_URI, values);
        if (uri != null) {
            Toast.makeText(this, "Event updated", Toast.LENGTH_SHORT).show();
        }
        //事件提醒
        long id = Long.parseLong(uri.getLastPathSegment());
        ContentValues contentValues = new ContentValues();
        contentValues.put(CalendarContract.Reminders.EVENT_ID, id);
        // 提前10分钟有提醒
        contentValues.put(CalendarContract.Reminders.MINUTES, 0);
        contentValues.put(CalendarContract.Reminders.METHOD, CalendarContract.Reminders.METHOD_ALERT);
        getContentResolver().insert(CalendarContract.Reminders.CONTENT_URI, contentValues);



        Cursor cursor = getContentResolver().query(CalendarContract.Reminders.CONTENT_URI,
                new String[]{CalendarContract.Reminders.MINUTES},
                CalendarContract.Reminders.EVENT_ID + " = ?",
                new String[]{String.valueOf(id)},
                null);

        if (cursor != null && cursor.moveToFirst()) {
            @SuppressLint("Range") int minutes = cursor.getInt(cursor.getColumnIndex(CalendarContract.Reminders.MINUTES));
            Log.d("Reminder", "Event has a reminder set for " + minutes + " minutes before.");
            cursor.close();
        }

        finish();
    }

    private boolean ifEventReachedMax() throws ParseException {

        String dateString = editStart.getText().toString();
        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm", Locale.getDefault());

        Calendar beginTime = Calendar.getInstance(TimeZone.getTimeZone("Asia/Shanghai"));  // Calendar类处理日期和时间.这里注意时区！
        // beginTime.set(eventYear, eventMonth, eventDay, 0, 0, 0);
        beginTime.setTimeInMillis(dateFormat.parse(dateString).getTime());
        beginTime.set(Calendar.HOUR_OF_DAY, 0);
        beginTime.set(Calendar.MINUTE, 0);
        beginTime.set(Calendar.SECOND, 0);
        long startMillis = beginTime.getTimeInMillis(); //获取19701月1日至今的毫秒数

        Calendar endTime = Calendar.getInstance(TimeZone.getTimeZone("Asia/Shanghai"));
        endTime.setTimeInMillis(dateFormat.parse(dateString).getTime());
        endTime.set(Calendar.HOUR_OF_DAY, 23);
        endTime.set(Calendar.MINUTE, 59);
        endTime.set(Calendar.SECOND, 59);
        long endMillis = endTime.getTimeInMillis();

        // 构建 Instances URI，设置查询范围
        Uri.Builder builder = CalendarContract.Instances.CONTENT_URI.buildUpon();
        ContentUris.appendId(builder, startMillis);
        ContentUris.appendId(builder, endMillis);

        // 查询字段，包括 ORIGINAL_ID
        String[] projection = new String[]{
                CalendarContract.Instances.EVENT_ID,
                CalendarContract.Instances.BEGIN,
                CalendarContract.Instances.TITLE,
        };

        // 筛选条件
        String selection = "(" + CalendarContract.Instances.BEGIN + " >= ?) AND (" + CalendarContract.Instances.BEGIN + " <= ?) AND (" + CalendarContract.Instances.OWNER_ACCOUNT + " = ?)";
        String[] selectionArgs = new String[]{String.valueOf(startMillis - 1000), String.valueOf(endMillis), "ADBC_calendar"};
        ContentResolver cr = getContentResolver(); // 访问其他应用的数据——包括联系人、日历、媒体库等
        Cursor cursor = cr.query(builder.build(), projection, selection, selectionArgs, null);

        if (cursor != null && cursor.getCount() >= MAX_EVENT_NUMBER) {
            //Toast.makeText(this, "事件数量：" + cursor.getCount(), Toast.LENGTH_SHORT).show();
            Toast.makeText(this, "所选日期事件数量已达上限！", Toast.LENGTH_SHORT).show();
            return true;
        }
        return false;
    }

    private long getCalendarId(String selectedCalendar) {
        String[] selectionArgs = new String[]{selectedCalendar};
        String[] projection1 = new String[]{CalendarContract.Calendars._ID, CalendarContract.Calendars.ACCOUNT_NAME};
        String selection = CalendarContract.Calendars.ACCOUNT_NAME + " = ?";
        Cursor cursor0 = null;
        long calendarId = -1;
        try {
            cursor0 = getContentResolver().query(
                    CalendarContract.Calendars.CONTENT_URI,
                    projection1,
                    selection,
                    selectionArgs,
                    null
            );
            if (cursor0 != null && cursor0.moveToFirst()) {
                calendarId = cursor0.getLong(0);
            }
        } finally {
            if (cursor0 != null) {
                cursor0.close();
            }
        }
        return calendarId;
    }

    // 格式化日期为字符串
    private String formatDate(long dateInMillis) {
        DateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm", Locale.getDefault());
        return formatter.format(new Date(dateInMillis));
    }

    private void datePick(View v) {
        int year = calendar.get(Calendar.YEAR);
        int month = calendar.get(Calendar.MONTH);
        int day = calendar.get(Calendar.DAY_OF_MONTH);
        int hour = calendar.get(Calendar.HOUR_OF_DAY);
        int minute = calendar.get(Calendar.MINUTE);


        DatePickerDialog datePickerDialog = new DatePickerDialog(EditEventActivity.this,
                (view, year1, monthOfYear, dayOfMonth) -> {
                    // 设置时间到时间选择器
                    TimePickerDialog timePickerDialog = new TimePickerDialog(EditEventActivity.this,
                            (view1, hourOfDay, minute1) -> {
                                if (hourOfDay < hour || (hourOfDay == hour && minute1 < minute)) {
                                    hourOfDay = hour;
                                    minute1 = minute;
                                }
                                // 这里可以更新界面显示选择的时间
                                calendar.set(Calendar.HOUR_OF_DAY, hourOfDay);
                                calendar.set(Calendar.MINUTE, minute1);
                                calendar.set(Calendar.YEAR, year1);
                                calendar.set(Calendar.MONTH, monthOfYear);
                                calendar.set(Calendar.DAY_OF_MONTH, dayOfMonth);
                                if (v.getId() == R.id.date_text || v.getId() == R.id.pick_button) {
                                    editStart.setText(android.text.format.DateFormat.format("yyyy-MM-dd HH:mm", calendar.getTime()));
                                    start.set(Calendar.HOUR_OF_DAY, hourOfDay);
                                    start.set(Calendar.MINUTE, minute1);
                                    start.set(Calendar.YEAR, year1);
                                    start.set(Calendar.MONTH, monthOfYear);
                                    start.set(Calendar.DAY_OF_MONTH, dayOfMonth);
                                    if (end.before(start)) {
                                        editEnd.setText(android.text.format.DateFormat.format("yyyy-MM-dd HH:mm", start.getTime()));
                                    }
                                } else if (v.getId() == R.id.date_text_end || v.getId() == R.id.pick_button_end) {
                                    end.set(Calendar.HOUR_OF_DAY, hourOfDay);
                                    end.set(Calendar.MINUTE, minute1);
                                    end.set(Calendar.YEAR, year1);
                                    end.set(Calendar.MONTH, monthOfYear);
                                    end.set(Calendar.DAY_OF_MONTH, dayOfMonth);
                                    if (calendar.before(start)) {
                                        editEnd.setText(android.text.format.DateFormat.format("yyyy-MM-dd HH:mm", start.getTime()));
                                    } else editEnd.setText(android.text.format.DateFormat.format("yyyy-MM-dd HH:mm", calendar.getTime()));
                                }

                            }, hour, minute, true);
                    timePickerDialog.show();
                }, year, month, day);
        datePickerDialog.getDatePicker().setMinDate(Calendar.getInstance().getTimeInMillis());
        datePickerDialog.show();
    }

    private static boolean isSameDay(long oldStartDate, long newStartDate) {
        Date oldDate = new Date(oldStartDate);
        Date newDate = new Date(newStartDate);
        // 使用 Calendar 提取年月日信息
        Calendar cal1 = Calendar.getInstance();
        Calendar cal2 = Calendar.getInstance();
        cal1.setTime(oldDate);
        cal2.setTime(newDate);
        // 比较年月日信息
        boolean sameDay = cal1.get(Calendar.YEAR) == cal2.get(Calendar.YEAR) &&
                cal1.get(Calendar.MONTH) == cal2.get(Calendar.MONTH) &&
                cal1.get(Calendar.DAY_OF_MONTH) == cal2.get(Calendar.DAY_OF_MONTH);
        return sameDay;
    }
}